package com.java.simple.smallspring.core.io;

import cn.hutool.core.lang.Assert;
import com.java.simple.smallspring.util.ClassUtil;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author zhoujunlin
 * @date 2022年08月19日 17:13
 * @desc
 */
public class ClassPathResource implements Resource {

    private final String path;
    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notBlank(path, "Path must not be null");
        this.path = path;
        this.classLoader = Objects.nonNull(classLoader) ? classLoader : ClassUtil.getDefaultClassLoader();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream resourceStream = classLoader.getResourceAsStream(path);
        if (Objects.isNull(resourceStream)) {
            throw new FileNotFoundException(this.path + " cannot be opened beacause it does not exist");
        }
        return resourceStream;
    }

}
